import { api } from '@/http/api'
import http from '@/http'

// 上传图片
const tpUploadApp = (file: any, ocrType = '000', billNo = ''): Promise<any> => {
  //传请求和文件
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    let content: any

    reader.onload = function (event) {
      content = event.target?.result
      compress(content, 450, async function (content0: any) {
        // console.log("final=" + content0.length / 1024 + "KB");
        // console.log(content0, 989);  //base64文件
        const [imgHead, imageURI] = content0.split(',')
        const suffix = imgHead.split('/')[1].split(';')[0] //获取图片后缀jpeg

        // imageURI为图片的base64编码，不包含头部部分：data:img/jpg;base64,
        const fileName = new Date().getTime() + '.' + suffix //随机文件名
        const imgfile = convertBase64UrlToImgFile(imageURI, fileName, 'image/' + suffix) //转换成file
        const formData = new FormData()
        formData.append('file', imgfile, fileName) //放到表单中，此处的file要和后台取文件时候的属性名称保持一致
        formData.append('type', ocrType)
        billNo ? formData.append('billNo', billNo) : '' //运单号
        // 上传请求
        const resPicture = await upAjax(formData)
        resolve(resPicture)
      })
    }
    reader.onerror = function () {
      // console.log("error");
    }
    // reader.readAsDataURL(file, "UTF-8");
    reader.readAsDataURL(file)
  })
}

// 压缩图片
const compress = (content: string, size: number, callback: any) => {
  if (content.length <= size * 1024) {
    callback(content)
    return
  }
  const canvas = document.createElement('canvas')
  const ctx: any = canvas.getContext('2d')
  const img = new Image()
  img.src = content
  img.onload = function () {
    const width = img.width
    const height = img.height
    canvas.width = width
    canvas.height = height
    // 铺底色
    ctx.fillStyle = '#fff'
    ctx.fillRect(0, 0, width, height)
    ctx.drawImage(img, 0, 0, width, height)
    const rate = (1024 * size) / content.length
    // console.log("size=" + size + " rate=" + rate);
    // console.log("**压缩前**" + content.length / 1024 + "KB");
    //进行压缩
    content = canvas.toDataURL('image/jpeg', rate)
    // console.log("**压缩后**" + content.length / 1024 + "KB");
    callback(content)
  }
}

// 有些浏览器(如edge)不支持new File，所以为了兼容，base64要先转换成blob再设置type，name，lastModifiedDate
// 属性间接转换成文件，而不推荐直接new File()的方式
const convertBase64UrlToImgFile = (urlData: any, fileName: any, fileType: any) => {
  const bytes = window.atob(urlData) //转换为byte
  //处理异常,将ascii码小于0的转换为大于0
  const ab = new ArrayBuffer(bytes.length)
  const ia = new Int8Array(ab)
  let i
  for (i = 0; i < bytes.length; i++) {
    ia[i] = bytes.charCodeAt(i)
  }
  //转换成文件，添加文件的type，name，lastModifiedDate属性
  const blob: any = new Blob([ab], {
    type: fileType
  })
  blob.lastModifiedDate = new Date()
  blob.name = fileName
  return blob
}

// 上传图片到后台
function upAjax(formData: any) {
  return new Promise((resolve, reject) => {
    http<string>({
      url: api.addUploadImage,
      method: 'post',
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      data: formData
    })
      .then((res: any) => {
        resolve(res)
      })
      .catch((error: any) => {
        resolve(error)
      })
  })
}

export default tpUploadApp
